package main

import (
	"bufio"
	"bytes"
	"gitee.com/simple-set/simple.io/src/event"
	"log"
	"os"
)

type EchoClient struct{}

func NewEchoClient() *EchoClient {
	return &EchoClient{}
}

func (e *EchoClient) Accept(session *event.Session) error {
	return nil
}

func (e *EchoClient) Disconnect(session *event.Session) error {
	return nil
}

func (e *EchoClient) Active(session *event.Session, value any) (any, error) {
	reader := bufio.NewReader(os.Stdin)
	for {
		if readInput, err := reader.ReadBytes('\n'); err != nil {
			log.Println("input error:", err)
			break
		} else {
			if string(bytes.TrimRight(readInput, "\n")) == "exit" {
				return nil, session.Close()
			}
			if err = session.Socket.WriterBytes(readInput); err != nil {
				log.Println("write error:", err)
			}
		}

		if readLine, err := session.Socket.Reader.ReadBytes('\n'); err != nil {
			return nil, err
		} else {
			readLine = bytes.TrimRight(readLine, "\n")
			log.Printf("%s, Received data=> %s", session.Socket.RemoteAddr().String(), string(readLine))
		}
	}
	return nil, session.Close()
}

type EchoServer struct{}

func NewEchoServer() *EchoServer {
	return &EchoServer{}
}

func (e *EchoServer) Accept(_ *event.Session) error {
	return nil
}

func (e *EchoServer) Disconnect(_ *event.Session) error {
	return nil
}

func (e *EchoServer) Active(session *event.Session, _ any) (any, error) {
	var buf = make([]byte, 1024)
	for {
		n, err := session.Socket.ReaderBytes(buf)
		if err != nil {
			return nil, err
		}
		if n > 0 {
			readLine := bytes.TrimRight(buf[:n], "\n")
			log.Printf("%s, Received message: %s\n", session.Socket.RemoteAddr().String(), string(readLine))
			if err := session.Socket.WriterBytes(buf[:n]); err != nil {
				return nil, err
			}
		}
	}
}
